<template>
  <view class="poop-page">
    <!-- 日历组件 -->
    <view class="calendar-container">
      <view class="calendar-header">
        <text class="month-title">{{ currentYear }}年{{ currentMonth }}月</text>
        <view class="calendar-nav">
          <text @click="prevMonth" class="nav-btn">上</text>
          <text @click="nextMonth" class="nav-btn">下</text>
        </view>
      </view>

      <view class="calendar-weekdays">
        <text v-for="(day, index) in weekDays" :key="index" class="weekday">{{ day }}</text>
      </view>

      <view class="calendar-days">
        <view
          v-for="(day, index) in calendarDays"
          :key="index"
          :class="[
            'calendar-day',
            day.isCurrentMonth ? 'current-month' : 'other-month',
            day.isToday ? 'today' : '',
            day.isSelected ? 'selected' : '',
            day.poopCount > 0 ? `poop-count-${getPoopCountClass(day.poopCount)}` : ''
          ]"
          @click="selectDate(day)"
        >
          <text class="day-number">{{ day.day }}</text>
          <text v-if="day.poopCount > 0" class="poop-count">{{ day.poopCount }}次</text>
        </view>
      </view>

      <view class="calendar-legend">
        <view class="legend-item">
          <view class="legend-color normal"></view>
          <text class="legend-text">1次</text>
        </view>
        <view class="legend-item">
          <view class="legend-color warning"></view>
          <text class="legend-text">2-3次</text>
        </view>
        <view class="legend-item">
          <view class="legend-color danger"></view>
          <text class="legend-text">4次以上</text>
        </view>
      </view>
    </view>

    <!-- 记录表单区域 -->
    <view v-if="showRecordForm" class="record-form">
      <!-- 便便状态展示 -->
      <view class="poop-status">
        <view class="status-title">
          <text>便便健康状态</text>
          <text class="status-emoji">{{ healthStatus.emoji }}</text>
        </view>
        <view class="status-desc">{{ healthStatus.description }}</view>
      </view>
      <!-- 拍照记录 -->
      <view class="section-title">拍照打卡</view>
      <view class="photo-section">
        <view class="take-photo-btn" @click="takePhoto">
          <text class="photo-icon">📷</text>
          <text class="photo-text">拍照打卡</text>
        </view>
        <!-- 照片缩略图展示 -->
        <view class="photo-preview" v-if="photoPath">
          <image class="preview-image" :src="photoPath" mode="aspectFill"></image>
          <view class="delete-photo" @click="deletePhoto">×</view>
        </view>
      </view>
      <!-- 便便形状选择 -->
      <view class="section-title">便便形状</view>
      <view class="poop-shapes">
        <view
          v-for="(shape, index) in poopShapes"
          :key="'shape-' + index"
          :class="['poop-shape-item', selectedShape === shape.value ? 'selected' : '']"
          @click="selectShape(shape.value)"
        >
          <text class="shape-emoji">{{ shape.emoji }}</text>
          <text class="shape-name">{{ shape.name }}</text>
        </view>
      </view>

      <!-- 便便颜色选择 -->
      <view class="section-title">便便颜色</view>
      <view class="poop-colors">
        <view
          v-for="(color, index) in poopColors"
          :key="'color-' + index"
          :class="['poop-color-item', selectedColor === color.value ? 'selected' : '']"
          @click="selectColor(color.value)"
        >
          <view class="color-circle" :style="{ backgroundColor: color.hex }"></view>
          <text class="color-name">{{ color.name }}</text>
        </view>
      </view>

      <!-- 记录时间 -->
      <view class="time-section">
        <view class="section-title">记录时间</view>
        <view class="time-picker">
          <picker mode="time" :value="selectedTime" @change="timeChange" class="picker">
            <view class="picker-value">{{ selectedTime }}</view>
          </picker>
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="note-section">
        <view class="section-title">备注信息</view>
        <textarea
          v-model="note"
          placeholder="记录一下今天的感受..."
          class="note-input"
          maxlength="100"
        ></textarea>
        <text class="note-count">{{ note.length }}/100</text>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" @click="submitRecord">记录一下</button>
         <button class="submit-btn" style="margin-top: 20px;" open-type="share">分享给好友</button>
      </view>
    </view>
    <!-- 历史记录 -->
    <view class="history-section" v-if="selectedDateRecords.length > 0">
      <view class="section-header">
        <view class="section-title">当日记录</view>
        <button class="report-btn" @click="generateReport">生成报告</button>
      </view>
      <view class="history-list">
        <view
          v-for="(record, index) in selectedDateRecords"
          :key="'history-' + index"
          class="history-item"
        >
          <view class="history-time">{{ record.time }}</view>
          <view class="history-info">
            <text class="history-emoji">{{ getShapeEmoji(record.shape) }}</text>
            <view
              class="history-color"
              :style="{ backgroundColor: getColorHex(record.color) }"
            ></view>
            <text class="history-note" v-if="record.note">{{ record.note }}</text>

            <!-- 照片缩略图 -->
            <view class="history-photo" v-if="record.hasPhoto && record.photoPath">
              <image
                class="history-photo-image"
                :src="record.photoPath"
                mode="aspectFill"
                @click="previewImage(record.photoPath)"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 报告弹窗 -->
    <view class="modal" v-if="showReportModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">便便健康报告</text>
          <text class="modal-close" @click="showReportModal = false">×</text>
        </view>
        <view class="modal-body">
          <view class="report-date">{{ formatDate(selectedDate) }}</view>
          <view class="report-records">
            <view
              v-for="(record, index) in selectedDateRecords"
              :key="'report-' + index"
              class="report-record-item"
            >
              <text class="report-time">{{ record.time }}</text>
              <text class="report-emoji">{{ getShapeEmoji(record.shape) }}</text>
              <view
                class="report-color"
                :style="{ backgroundColor: getColorHex(record.color) }"
              ></view>
              <text class="report-note" v-if="record.note">{{ record.note }}</text>
            </view>
          </view>
          <view class="report-summary">
            <text class="summary-title">健康分析</text>
            <text class="summary-content">{{ reportSummary }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <button class="share-btn" @click="shareReport">分享给朋友</button>
          <button class="close-btn" @click="showReportModal = false">关闭</button>
        </view>
      </view>
    </view>
    <!-- 用于生成分享图片的canvas，设置为不可见 -->
    <canvas
      canvas-id="reportCanvas"
      style="width: 750px; height: 1500px; position: fixed; left: -2000px; top: 0"
    ></canvas>
  </view>
  <FloatButton />
</template>

<script>
import FloatButton from '@/components/FloatButton.vue'
import { getShareAppMessageConfig, getShareTimelineConfig } from '../../utils/share.js'
export default {
  components: {
    FloatButton
  },
  data() {
    return {
      // 日历相关
      currentDate: new Date(),
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      selectedDate: new Date(),
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarDays: [],
      showRecordForm: false,

      // 原有数据
      yesterdayCount: 1,
      todayCount: 0,

      // 报告相关
      showReportModal: false,
      reportSummary: '',
      weeklyCount: 5,
      selectedShape: 'normal',
      selectedColor: 'brown',
      selectedTime: this.getCurrentTime(),
      note: '',
      photoPath: '', // 存储拍照的临时路径
      poopShapes: [
        { value: 'separate', name: '分离状', emoji: '💩', description: '排便困难' },
        { value: 'lumpy', name: '硬块状', emoji: '🥥', description: '轻度便秘' },
        { value: 'cracked', name: '裂缝状', emoji: '🌰', description: '正常' },
        { value: 'normal', name: '香蕉状', emoji: '🍌', description: '理想状态' },
        { value: 'soft', name: '软便状', emoji: '🍦', description: '轻度腹泻' },
        { value: 'mushy', name: '糊状', emoji: '🍯', description: '重度腹泻' },
        { value: 'watery', name: '水状', emoji: '💧', description: '严重腹泻' }
      ],
      poopColors: [
        { value: 'brown', name: '健康棕色', hex: '#8B4513' },
        { value: 'golden', name: '金黄色', hex: '#DAA520' },
        { value: 'green', name: '绿色', hex: '#228B22' },
        { value: 'red', name: '红色', hex: '#B22222' },
        { value: 'black', name: '黑色', hex: '#2F4F4F' },
        { value: 'gray', name: '灰白色', hex: '#A9A9A9' }
      ],
      poopHistory: []
    }
  },
  computed: {
    healthStatus() {
      // 根据选择的形状和颜色计算健康状态
      const shape = this.poopShapes.find(s => s.value === this.selectedShape)

      if (this.selectedShape === 'normal' && this.selectedColor === 'brown') {
        return { emoji: '😊', description: '太棒了！你的便便状态非常健康！' }
      } else if (['cracked', 'normal'].includes(this.selectedShape)) {
        return { emoji: '🙂', description: '不错哦，便便状态良好！' }
      } else if (['separate', 'lumpy'].includes(this.selectedShape)) {
        return { emoji: '😐', description: '便便有点干硬，多喝水多吃纤维！' }
      } else if (['soft', 'mushy'].includes(this.selectedShape)) {
        return { emoji: '😟', description: '便便有点软，注意饮食清淡！' }
      } else if (this.selectedShape === 'watery' || ['red', 'black'].includes(this.selectedColor)) {
        return { emoji: '😨', description: '便便状态异常，建议咨询医生！' }
      }

      return { emoji: '🤔', description: '记录你的便便，关注肠道健康！' }
    },

    selectedDateRecords() {
      // 获取选中日期的格式化字符串
      const selectedDateStr = this.formatDate(this.selectedDate)

      // 过滤出选中日期的记录并按时间倒序排列（最新的在前面）
      return this.poopHistory
        .filter(record => record.date === selectedDateStr)
        .sort((a, b) => {
          // 将时间转换为可比较的格式
          const timeA = a.time.split(':').map(Number)
          const timeB = b.time.split(':').map(Number)

          // 比较小时
          if (timeB[0] !== timeA[0]) {
            return timeB[0] - timeA[0]
          }
          // 如果小时相同，比较分钟
          return timeB[1] - timeA[1]
        })
    }
  },
  // 分享到聊天
  onShareAppMessage() {
    return getShareAppMessageConfig({
      title: '拉屎打卡 - 安记录丨工具舱',
      path: '/pages-sub/poop/index',
      imageUrl: '/static/share-img.png'
    })
  },
  // 分享到朋友圈
  onShareTimeline() {
    return getShareTimelineConfig({
      title: '拉屎打卡 - 安记录丨工具舱',
      imageUrl: '/static/share-img.png'
    })
  },
  mounted() {
    this.generateCalendar()
    this.loadPoopHistory()
  },
  methods: {
    // 加载本地存储的拉屎记录
    loadPoopHistory() {
      const monthStr = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}`
      const allRecords = uni.getStorageSync('poopHistory') || []
      
      // 过滤出当前月的记录
      this.poopHistory = allRecords.filter(record => {
        return record.date.startsWith(monthStr)
      })
      
      // 更新日历和选中日期的记录
      this.generateCalendar()
    },

    // 保存拉屎记录到本地存储
    // 云数据库写入由 submitRecord 处理，无需本地存储

    // 日历相关方法
    generateCalendar() {
      const year = this.currentYear
      const month = this.currentMonth - 1 // JavaScript月份从0开始

      // 获取当月第一天
      const firstDay = new Date(year, month, 1)
      // 获取当月最后一天
      const lastDay = new Date(year, month + 1, 0)

      // 当月天数
      const daysInMonth = lastDay.getDate()

      // 第一天是星期几（0是星期日）
      const firstDayOfWeek = firstDay.getDay()

      // 生成日历数据
      let days = []

      // 上个月的日期
      const prevMonthLastDay = new Date(year, month, 0).getDate()
      for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        const day = prevMonthLastDay - i
        const date = new Date(year, month - 1, day)
        days.push({
          day,
          date,
          isCurrentMonth: false,
          isToday: this.isToday(date),
          isSelected: this.isSameDate(date, this.selectedDate),
          poopCount: this.getPoopCountForDate(this.formatDate(date))
        })
      }

      // 当月的日期
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i)
        days.push({
          day: i,
          date,
          isCurrentMonth: true,
          isToday: this.isToday(date),
          isSelected: this.isSameDate(date, this.selectedDate),
          poopCount: this.getPoopCountForDate(this.formatDate(date))
        })
      }

      // 下个月的日期
      const remainingDays = 42 - days.length // 6行7列 = 42
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month + 1, i)
        days.push({
          day: i,
          date,
          isCurrentMonth: false,
          isToday: this.isToday(date),
          isSelected: this.isSameDate(date, this.selectedDate),
          poopCount: this.getPoopCountForDate(this.formatDate(date))
        })
      }

      this.calendarDays = days
    },

    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentYear--
        this.currentMonth = 12
      } else {
        this.currentMonth--
      }
      this.generateCalendar()
    },

    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentYear++
        this.currentMonth = 1
      } else {
        this.currentMonth++
      }
      this.generateCalendar()
    },

    selectDate(day) {
      this.selectedDate = new Date(day.date)
      this.showRecordForm = true

      // 更新日历中的选中状态
      this.calendarDays = this.calendarDays.map(d => ({
        ...d,
        isSelected: this.isSameDate(d.date, this.selectedDate)
      }))

      // 立即加载选中日期的记录
      this.loadPoopHistory()
    },

    isToday(date) {
      const today = new Date()
      return this.isSameDate(date, today)
    },

    isSameDate(date1, date2) {
      return (
        date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate()
      )
    },

    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    getPoopCountForDate(dateStr) {
      return this.poopHistory.filter(record => record.date === dateStr).length
    },

    getPoopCountClass(count) {
      if (count === 0) return ''
      if (count === 1) return 'normal'
      if (count >= 2 && count <= 3) return 'warning'
      return 'danger'
    },

    // 原有方法
    getCurrentTime() {
      const now = new Date()
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },
    selectShape(shape) {
      this.selectedShape = shape
    },
    selectColor(color) {
      this.selectedColor = color
    },
    timeChange(e) {
      this.selectedTime = e.detail.value
    },
    submitRecord() {
      // 获取选中日期
      const selectedDate = this.selectedDate
      const year = selectedDate.getFullYear()
      const month = String(selectedDate.getMonth() + 1).padStart(2, '0')
      const day = String(selectedDate.getDate()).padStart(2, '0')
      const dateStr = `${year}-${month}-${day}`

      // 准备记录数据
      const recordData = {
        date: dateStr,
        shape: this.selectedShape,
        color: this.selectedColor,
        time: this.selectedTime,
        note: this.note,
        hasPhoto: !!this.photoPath, // 是否有照片
        photoPath: this.photoPath || '' // 照片路径
      }

      // 获取现有记录
      const allRecords = uni.getStorageSync('poopHistory') || []
      
      // 添加新记录
      allRecords.push(recordData)
      
      // 保存到本地存储
      uni.setStorageSync('poopHistory', allRecords)

      // 重置表单
      this.note = ''
      // 不重置照片，让用户可以继续使用同一张照片记录

      uni.showToast({ title: '记录成功！', icon: 'success' })
      setTimeout(() => {
        uni.$emit && uni.$emit('refreshRecord')
        uni.navigateBack()
      }, 500)
      this.loadPoopHistory()
    },
    getShapeEmoji(shapeValue) {
      const shape = this.poopShapes.find(s => s.value === shapeValue)
      return shape ? shape.emoji : '💩'
    },
    getColorHex(colorValue) {
      const color = this.poopColors.find(c => c.value === colorValue)
      return color ? color.hex : '#8B4513'
    },

    // 报告功能
    generateReport() {
      // 生成报告摘要
      this.generateReportSummary()
      // 显示报告弹窗
      this.showReportModal = true
    },

    generateReportSummary() {
      // 分析当日记录
      const records = this.selectedDateRecords
      if (records.length === 0) {
        this.reportSummary = '今日暂无记录，请保持规律排便习惯。'
        return
      }

      // 分析形状
      const shapes = records.map(r => r.shape)
      const shapeTypes = [...new Set(shapes)]

      // 分析颜色
      const colors = records.map(r => r.color)
      const colorTypes = [...new Set(colors)]

      // 生成摘要
      let summary = ''

      // 频次分析
      if (records.length === 1) {
        summary += '今日排便1次，'
      } else if (records.length >= 2 && records.length <= 3) {
        summary += `今日排便${records.length}次，频率正常，`
      } else if (records.length > 3) {
        summary += `今日排便${records.length}次，频率偏高，`
      }

      // 形状分析
      if (shapeTypes.includes('normal')) {
        summary += '粪便形状良好，'
      } else if (shapeTypes.includes('separate') || shapeTypes.includes('lumpy')) {
        summary += '粪便偏硬，可能存在便秘情况，建议多喝水、多吃纤维素食物，'
      } else if (
        shapeTypes.includes('soft') ||
        shapeTypes.includes('mushy') ||
        shapeTypes.includes('watery')
      ) {
        summary += '粪便偏软，可能存在消化不良情况，建议注意饮食调理，'
      }

      // 颜色分析
      if (colorTypes.includes('brown')) {
        summary += '颜色正常。'
      } else if (colorTypes.includes('golden')) {
        summary += '颜色偏黄，可能与饮食有关。'
      } else {
        summary += '颜色异常，如持续异常请咨询医生。'
      }

      // 总体建议
      summary += '保持规律作息和均衡饮食有助于肠道健康。'

      this.reportSummary = summary
    },

    shareReport() {
      // 显示加载提示
      uni.showLoading({
        title: '正在生成分享图片...'
      })

      // 收集需要加载的照片
      const photosToLoad = []
      this.selectedDateRecords.forEach(record => {
        if (record.hasPhoto && record.photoPath) {
          photosToLoad.push(record.photoPath)
        }
      })

      // 先加载所有照片，然后再绘制canvas
      this.loadPhotos(photosToLoad)
        .then(photoInfos => {
          this.drawReportCanvas(photoInfos)
        })
        .catch(err => {
          console.error('加载照片失败', err)
          // 即使照片加载失败，也继续绘制其他内容
          this.drawReportCanvas([])
        })
    },

    // 加载所有照片
    loadPhotos(photoPaths) {
      if (!photoPaths || photoPaths.length === 0) {
        return Promise.resolve([])
      }

      const promises = photoPaths.map(path => {
        return new Promise((resolve, reject) => {
          uni.getImageInfo({
            src: path,
            success: res => {
              resolve({
                path: path,
                width: res.width,
                height: res.height
              })
            },
            fail: err => {
              console.error('获取图片信息失败', err)
              reject(err)
            }
          })
        })
      })

      return Promise.all(promises)
    },

    // 绘制报告画布
    drawReportCanvas(photoInfos) {
      // 获取 canvas 上下文
      const ctx = uni.createCanvasContext('reportCanvas', this)

      // 设置背景 - 使用更大的画布以容纳照片
      const canvasWidth = 750
      const canvasHeight = 1500 // 增加高度以容纳照片

      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)

      // 绘制标题背景
      ctx.fillStyle = '#8B5CF6'
      ctx.fillRect(0, 0, 750, 120)

      // 绘制标题
      ctx.fillStyle = '#ffffff'
      ctx.font = 'bold 40px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText('便便健康报告', 375, 70)

      // 绘制日期
      const dateStr = this.formatDate(this.selectedDate)
      ctx.fillStyle = '#666666'
      ctx.font = '28px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText(`日期: ${dateStr}`, 375, 160)

      // 绘制分割线
      ctx.strokeStyle = '#eeeeee'
      ctx.lineWidth = 2
      ctx.beginPath()
      ctx.moveTo(50, 180)
      ctx.lineTo(700, 180)
      ctx.stroke()

      // 绘制记录标题
      ctx.fillStyle = '#8B5CF6'
      ctx.font = 'bold 32px sans-serif'
      ctx.textAlign = 'left'
      ctx.fillText('今日记录', 50, 230)

      // 绘制记录列表
      let yPos = 280
      const records = this.selectedDateRecords
      // 创建照片信息的映射，方便查找
      const photoMap = {}
      photoInfos.forEach(info => {
        photoMap[info.path] = info
      })

      if (records.length === 0) {
        ctx.fillStyle = '#999999'
        ctx.font = '28px sans-serif'
        ctx.fillText('今日暂无记录', 50, yPos)
        yPos += 50
      } else {
        records.forEach((record, index) => {
          // 绘制时间
          ctx.fillStyle = '#999999'
          ctx.font = '24px sans-serif'
          ctx.fillText(record.time, 50, yPos)

          // 绘制形状emoji
          ctx.font = '32px sans-serif'
          ctx.fillText(this.getShapeEmoji(record.shape), 150, yPos)

          // 绘制颜色圆点
          ctx.fillStyle = this.getColorHex(record.color)
          ctx.beginPath()
          ctx.arc(220, yPos - 10, 15, 0, Math.PI * 2)
          ctx.fill()

          // 绘制备注，处理长备注换行
          ctx.fillStyle = '#666666'
          ctx.font = '24px sans-serif'

          const note = record.note || '无备注'
          const noteMaxWidth = 400 // 备注最大宽度

          // 检查备注是否需要换行
          if (ctx.measureText(note).width > noteMaxWidth) {
            // 简单处理：截断显示并添加省略号
            let displayNote = note
            while (
              ctx.measureText(displayNote + '...').width > noteMaxWidth &&
              displayNote.length > 0
            ) {
              displayNote = displayNote.slice(0, -1)
            }
            ctx.fillText(displayNote + '...', 250, yPos)
          } else {
            ctx.fillText(note, 250, yPos)
          }

          yPos += 60

          // 如果有照片，绘制照片
          if (record.hasPhoto && record.photoPath && photoMap[record.photoPath]) {
            const photoInfo = photoMap[record.photoPath]

            // 计算照片尺寸，保持宽高比
            const maxPhotoWidth = 300
            const maxPhotoHeight = 200
            let photoWidth, photoHeight

            if (photoInfo.width > photoInfo.height) {
              // 横向照片
              photoWidth = Math.min(maxPhotoWidth, photoInfo.width)
              photoHeight = (photoInfo.height / photoInfo.width) * photoWidth
            } else {
              // 纵向照片
              photoHeight = Math.min(maxPhotoHeight, photoInfo.height)
              photoWidth = (photoInfo.width / photoInfo.height) * photoHeight
            }

            // 绘制照片边框
            ctx.strokeStyle = '#e0e0e0'
            ctx.lineWidth = 1
            ctx.strokeRect(50, yPos, photoWidth, photoHeight)

            // 绘制照片
            ctx.drawImage(photoInfo.path, 50, yPos, photoWidth, photoHeight)

            // 更新位置
            yPos += photoHeight + 20
          }

          // 绘制分隔线
          if (index < records.length - 1) {
            ctx.strokeStyle = '#f5f5f5'
            ctx.beginPath()
            ctx.moveTo(50, yPos - 10)
            ctx.lineTo(700, yPos - 10)
            ctx.stroke()
          }
        })
      }

      // 绘制分割线
      ctx.strokeStyle = '#eeeeee'
      ctx.lineWidth = 2
      ctx.beginPath()
      ctx.moveTo(50, yPos)
      ctx.lineTo(700, yPos)
      ctx.stroke()

      // 绘制健康分析标题
      yPos += 50
      ctx.fillStyle = '#8B5CF6'
      ctx.font = 'bold 32px sans-serif'
      ctx.fillText('健康分析', 50, yPos)

      // 绘制健康分析内容
      yPos += 50
      ctx.fillStyle = '#666666'
      ctx.font = '28px sans-serif'

      // 改进的文本换行处理
      const summary = this.reportSummary
      const maxWidth = 600 // 稍微减小最大宽度，留出边距

      // 更细粒度的分词，同时处理中文和英文
      const textArr = summary.split('').reduce((acc, char) => {
        if (/[，。！？,.!?;；]/.test(char)) {
          // 标点符号与前面的文字一起
          if (acc.length > 0) {
            acc[acc.length - 1] += char
          } else {
            acc.push(char)
          }
        } else if (/\s/.test(char)) {
          // 空格单独成词
          acc.push(char)
        } else {
          // 检查前一个是否是标点，如果不是则合并
          if (acc.length > 0 && !/[，。！？,.!?;；\s]$/.test(acc[acc.length - 1])) {
            acc[acc.length - 1] += char
          } else {
            acc.push(char)
          }
        }
        return acc
      }, [])

      let line = ''
      let lineWidth = 0

      // 逐字符绘制，确保每行不超过最大宽度
      for (let i = 0; i < textArr.length; i++) {
        const word = textArr[i]
        const wordWidth = ctx.measureText(word).width

        // 当前行加上新词会超出最大宽度，需要换行
        if (lineWidth + wordWidth > maxWidth) {
          ctx.fillText(line, 50, yPos)
          line = word
          lineWidth = wordWidth
          yPos += 40 // 行间距
        } else {
          // 当前行可以容纳新词
          line += word
          lineWidth += wordWidth
        }
      }

      // 绘制最后一行
      if (line) {
        ctx.fillText(line, 50, yPos)
      }

      // 绘制底部标识，确保有足够的底部间距
      yPos += 80 // 添加额外间距

      // 确保底部标识不会太靠下，超出画布
      const minBottomPosition = 950
      const maxBottomPosition = canvasHeight - 50

      if (yPos < minBottomPosition) {
        // 如果内容较少，使用默认位置
        yPos = minBottomPosition
      } else if (yPos > maxBottomPosition) {
        // 如果内容太多，使用最大位置
        yPos = maxBottomPosition
      }

      ctx.fillStyle = '#999999'
      ctx.font = '24px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText('排便打卡 - 关注肠道健康 - 仅供参考', 375, yPos)

      // 绘制完成后保存图片
      ctx.draw(false, () => {
        setTimeout(() => {
          uni.canvasToTempFilePath(
            {
              canvasId: 'reportCanvas',
              width: canvasWidth,
              height: canvasHeight,
              destWidth: canvasWidth,
              destHeight: canvasHeight,
              fileType: 'png',
              quality: 1,
              success: resp => {
                uni.hideLoading()

                // 保存图片到相册
                uni.saveImageToPhotosAlbum({
                  filePath: resp.tempFilePath,
                  success: () => {
                    // 显示分享操作菜单
                    uni.showActionSheet({
                      itemList: ['分享到微信'],
                      success: res => {
                        // 实际项目中可以接入微信分享SDK
                        uni.showShareImageMenu({
                          path: resp.tempFilePath,
                          success: () => {
                            uni.showToast({
                              title: '分享成功',
                              icon: 'success'
                            })
                          },
                          fail: err => {
                            console.error('分享失败', err)
                            uni.showToast({
                              title: '分享失败',
                              icon: 'none'
                            })
                          }
                        })
                      }
                    })
                  },
                  fail: err => {
                    console.error('保存图片失败', err)
                    uni.showToast({
                      title: '保存图片失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail: err => {
                uni.hideLoading()
                console.error('生成图片失败', err)
                uni.showToast({
                  title: '生成图片失败',
                  icon: 'none'
                })
              }
            },
            this
          )
        }, 300) // 延迟确保canvas绘制完成
      })
    },

    // 拍照功能
    takePhoto() {
      uni.chooseImage({
        count: 1, // 最多可以选择的图片张数
        sourceType: ['camera'], // 只使用相机
        success: res => {
          // 获取临时文件路径
          const tempFilePath = res.tempFilePaths[0]

          // 将照片保存到本地
          this.savePhotoToLocal(tempFilePath)
        },
        fail: err => {
          console.error('拍照失败', err)
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          })
        }
      })
    },

    // 保存照片到本地
    savePhotoToLocal(tempFilePath) {
      // 生成唯一文件名
      const fileName = `poop_photo_${Date.now()}.jpg`
      const fileManager = uni.getFileSystemManager()

      // 保存到本地用户目录
      const localPath = `${uni.env.USER_DATA_PATH}/${fileName}`

      fileManager.saveFile({
        tempFilePath: tempFilePath,
        filePath: localPath,
        success: res => {
          console.log('照片保存成功', res)
          this.photoPath = res.savedFilePath
        },
        fail: err => {
          console.error('照片保存失败', err)
          uni.showToast({
            title: '照片保存失败',
            icon: 'none'
          })
        }
      })
    },

    // 删除照片
    deletePhoto() {
      if (!this.photoPath) return

      const fileManager = uni.getFileSystemManager()

      fileManager.unlink({
        filePath: this.photoPath,
        success: () => {
          console.log('照片删除成功')
          this.photoPath = ''
        },
        fail: err => {
          console.error('照片删除失败', err)
        }
      })
    },

    // 预览图片
    previewImage(imagePath) {
      if (!imagePath) return

      uni.previewImage({
        urls: [imagePath],
        current: imagePath
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$primary: #f4c242;
$secondary: #8b4513;
$bg: #f8f8f8;
$card-bg: #fff;
$shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
$radius: 16rpx;
$border: 2rpx solid $primary;
$normal: #4caf50;
$warning: #ff9800;
$danger: #f44336;

.poop-page {
  background: $bg;
  min-height: 100vh;
  padding: 20rpx 30rpx 40rpx;
}

// 日历样式
.calendar-container {
  background-color: $card-bg;
  border-radius: $radius;
  padding: 20rpx;
  box-shadow: $shadow;
  margin-bottom: 30rpx;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0 20rpx;

  .month-title {
    font-size: 36rpx;
    font-weight: bold;
    color: $secondary;
  }

  .calendar-nav {
    display: flex;
    gap: 30rpx;

    .nav-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba($primary, 0.1);
      border-radius: 50%;
      font-size: 32rpx;
      color: $primary;
      font-weight: bold;
    }
  }
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 10rpx;

  .weekday {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 0;
  }
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 8rpx;

  .calendar-day {
    position: relative;
    height: 80rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 8rpx;

    &.current-month {
      background-color: rgba($primary, 0.05);
    }

    &.other-month {
      background-color: #f0f0f0;
      opacity: 0.6;

      .day-number {
        color: #aaa;
      }
    }

    &.today {
      border: 2rpx solid $primary;
    }

    &.selected {
      background-color: rgba($primary, 0.2);
      border: 2rpx solid $primary;
    }

    &.poop-count-normal {
      background-color: rgba($normal, 0.2);
    }

    &.poop-count-warning {
      background-color: rgba($warning, 0.2);
    }

    &.poop-count-danger {
      background-color: rgba($danger, 0.2);
    }

    .day-number {
      font-size: 28rpx;
      color: #333;
    }

    .poop-count {
      position: absolute;
      bottom: 5rpx;
      font-size: 20rpx;
      color: #666;
    }
  }
}

.calendar-legend {
  display: flex;
  justify-content: center;
  gap: 30rpx;
  margin-top: 20rpx;
  padding-top: 10rpx;
  border-top: 1rpx solid #eee;

  .legend-item {
    display: flex;
    align-items: center;

    .legend-color {
      width: 20rpx;
      height: 20rpx;
      border-radius: 4rpx;
      margin-right: 8rpx;

      &.normal {
        background-color: rgba($normal, 0.6);
      }

      &.warning {
        background-color: rgba($warning, 0.6);
      }

      &.danger {
        background-color: rgba($danger, 0.6);
      }
    }

    .legend-text {
      font-size: 22rpx;
      color: #666;
    }
  }
}

.record-form {
  margin-top: 30rpx;
}

// 原有样式

// 原有样式
.poop-status {
  background-color: $card-bg;
  border-radius: $radius;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: $shadow;

  .status-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 10rpx;

    .status-emoji {
      font-size: 48rpx;
    }
  }

  .status-desc {
    font-size: 28rpx;
    color: #666;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 30rpx 0 20rpx;
  color: $secondary;
}

.poop-shapes {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;

  .poop-shape-item {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: calc(25% - 15rpx);
    box-shadow: $shadow;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &.selected {
      border-color: $primary;
      background-color: rgba($primary, 0.1);
      transform: scale(1.05);
    }

    .shape-emoji {
      font-size: 40rpx;
      margin-bottom: 10rpx;
    }

    .shape-name {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.poop-colors {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;

  .poop-color-item {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: calc(33.33% - 14rpx);
    box-shadow: $shadow;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &.selected {
      border-color: $primary;
      background-color: rgba($primary, 0.1);
      transform: scale(1.05);
    }

    .color-circle {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-bottom: 10rpx;
    }

    .color-name {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.time-section {
  margin-top: 30rpx;

  .time-picker {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 20rpx;
    box-shadow: $shadow;

    .picker {
      width: 100%;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .picker-value {
      font-size: 36rpx;
      color: $secondary;
      font-weight: bold;
    }
  }
}

.note-section {
  position: relative;
  margin-top: 30rpx;

  .note-input {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 20rpx;
    width: calc(100% - 40rpx);
    height: 160rpx;
    font-size: 28rpx;
    box-shadow: $shadow;
  }

  .note-count {
    position: absolute;
    right: 20rpx;
    bottom: 10rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.submit-section {
  margin-top: 40rpx;
  padding: 20rpx 0;

  .submit-btn {
    background-color: $primary;
    color: #fff;
    border-radius: 50rpx;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    font-weight: bold;
    box-shadow: 0 4rpx 12rpx rgba($primary, 0.4);

    &:active {
      transform: scale(0.98);
    }
  }
}

.history-section {
  margin-top: 40rpx;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .report-btn {
      font-size: 24rpx;
      padding: 8rpx 20rpx;
      background-color: $primary;
      color: #fff;
      border-radius: 30rpx;
      border: none;
      box-shadow: 0 2rpx 8rpx rgba($primary, 0.3);
    }
  }

  .history-list {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 10rpx;
    box-shadow: $shadow;
  }

  .history-item {
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .history-time {
      font-size: 26rpx;
      color: #999;
      margin-bottom: 10rpx;
      font-weight: bold;
    }

    .history-info {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .history-emoji {
        font-size: 36rpx;
        margin-right: 20rpx;
      }

      .history-color {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .history-note {
        font-size: 24rpx;
        color: #666;
        margin-top: 10rpx;
        width: 100%;
        font-style: italic;
      }

      .history-photo {
        margin-top: 15rpx;
        width: 100%;

        .history-photo-image {
          width: 150rpx;
          height: 150rpx;
          border-radius: 8rpx;
          object-fit: cover;
        }
      }
    }
  }
}

// 拍照功能样式
.photo-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;

  .take-photo-btn {
    background-color: $card-bg;
    border-radius: $radius;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 200rpx;
    height: 200rpx;
    box-shadow: $shadow;
    border: 2rpx dashed #ccc;

    .photo-icon {
      font-size: 60rpx;
      margin-bottom: 10rpx;
    }

    .photo-text {
      font-size: 24rpx;
      color: #666;
    }
  }

  .photo-preview {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    border-radius: $radius;
    overflow: hidden;
    box-shadow: $shadow;

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .delete-photo {
      position: absolute;
      top: 5rpx;
      right: 5rpx;
      width: 40rpx;
      height: 40rpx;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
    }
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .modal-content {
    width: 80%;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .modal-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;

      .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        color: $primary;
      }

      .modal-close {
        font-size: 40rpx;
        color: #999;
        padding: 0 20rpx;
      }
    }

    .modal-body {
      padding: 30rpx;
      flex: 1;
      overflow-y: auto;

      .report-date {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
        text-align: center;
      }

      .report-records {
        margin-bottom: 30rpx;

        .report-record-item {
          display: flex;
          align-items: center;
          padding: 15rpx 0;
          border-bottom: 1px solid #f5f5f5;

          .report-time {
            font-size: 24rpx;
            color: #999;
            width: 120rpx;
          }

          .report-emoji {
            font-size: 36rpx;
            margin: 0 20rpx;
          }

          .report-color {
            width: 30rpx;
            height: 30rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }

          .report-note {
            font-size: 26rpx;
            color: #666;
            flex: 1;
          }
        }
      }

      .report-summary {
        background-color: #f9f9f9;
        padding: 20rpx;
        border-radius: 10rpx;

        .summary-title {
          font-size: 28rpx;
          font-weight: bold;
          color: $primary;
          margin-bottom: 10rpx;
          display: block;
        }

        .summary-content {
          font-size: 26rpx;
          color: #666;
          line-height: 1.6;
        }
      }
    }

    .modal-footer {
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #eee;

      button {
        flex: 1;
        margin: 0 10rpx;
        font-size: 28rpx;
        padding: 15rpx 0;
        border-radius: 40rpx;
      }

      .share-btn {
        background-color: $primary;
        color: #fff;
      }

      .close-btn {
        background-color: #f5f5f5;
        color: #666;
      }
    }
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .modal-content {
    width: 80%;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .modal-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;

      .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        color: $primary;
      }

      .modal-close {
        font-size: 40rpx;
        color: #999;
        padding: 0 20rpx;
      }
    }

    .modal-body {
      padding: 30rpx;
      flex: 1;
      overflow-y: auto;

      .report-date {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
        text-align: center;
      }

      .report-records {
        margin-bottom: 30rpx;

        .report-record-item {
          display: flex;
          align-items: center;
          padding: 15rpx 0;
          border-bottom: 1px solid #f5f5f5;

          .report-time {
            font-size: 24rpx;
            color: #999;
            width: 120rpx;
          }

          .report-emoji {
            font-size: 36rpx;
            margin: 0 20rpx;
          }

          .report-color {
            width: 30rpx;
            height: 30rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }

          .report-note {
            font-size: 26rpx;
            color: #666;
            flex: 1;
          }
        }
      }

      .report-summary {
        background-color: #f9f9f9;
        padding: 20rpx;
        border-radius: 10rpx;

        .summary-title {
          font-size: 28rpx;
          font-weight: bold;
          color: $primary;
          margin-bottom: 10rpx;
          display: block;
        }

        .summary-content {
          font-size: 26rpx;
          color: #666;
          line-height: 1.6;
        }
      }
    }

    .modal-footer {
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #eee;

      button {
        flex: 1;
        margin: 0 10rpx;
        font-size: 28rpx;
        padding: 15rpx 0;
        border-radius: 40rpx;
      }

      .share-btn {
        background-color: $primary;
        color: #fff;
      }

      .close-btn {
        background-color: #f5f5f5;
        color: #666;
      }
    }
  }
}
</style>
